/* 
 * Copyright [2018] [Alex/libo(liboware@gmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.infodb.user.service.impl;

import com.hyts.infodb.enums.SystemConfiguration;
import com.hyts.infodb.enums.SystemConfiguration.MessageConfiguration;
import com.hyts.infodb.enums.SystemConfiguration.ResultConfiguration;
import com.hyts.infodb.user.bean.bo.UserBO;
import com.hyts.infodb.user.bean.dto.LoginParamDTO;
import com.hyts.infodb.user.bean.dto.LoginResultDTO;
import com.hyts.infodb.user.bean.dto.UserDTO;
import com.hyts.infodb.user.bean.po.AccountPO;
import com.hyts.infodb.user.bean.vo.UserVO;
import com.hyts.infodb.user.dao.AccountDAO;
import com.hyts.infodb.user.service.LoginService;
import com.hyts.infodb.user.service.UserService;
import com.hyts.infodb.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.text.DateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;

/** 
 * @author LiBo/Alex
 * @version V1.0
 */
@Slf4j
@Service
public class LoginServiceImpl implements LoginService {


    @Autowired(required = false)
    AccountDAO accountDAO;

    @Autowired
    UserService userService;


    @Override
    public LoginResultDTO login(LoginParamDTO dto) {
        LoginResultDTO resultDTO = new LoginResultDTO();
        //用户名或者密码为空校验
        if(StringUtils.isEmpty(dto.getUserName()) && StringUtils.isEmpty(dto.getEmail())) {
        	resultDTO.failure(MessageConfiguration.LOGIN);
            //覆盖原有操作，否则会输出默认语句
        	resultDTO.setMessage("用户名或者邮箱不允许为空！");
            return resultDTO;
        }else if(StringUtils.isEmpty(dto.getPassword())){
        	resultDTO.failure(MessageConfiguration.LOGIN);
            resultDTO.setMessage("密码不允许为空！");
            return resultDTO;
        }
        UserBO bo = new UserBO();
        bo.setUserName(dto.getUserName()).setPassword(dto.getPassword());
        UserDTO result = login(bo);
        if(result.getCode() == ResultConfiguration.SUCCESS.getCode()) {
        	resultDTO.success(MessageConfiguration.LOGIN);
        	resultDTO.setMessage(result.getMessage());
            UserVO userVO = userService.getUser(dto.getUserName());
            boolean flag = changeLoginLogData(userVO.getContent().getId());
            if(flag){
                log.info("更新上一次登录时间成功!");
            }
        }else if(result.getCode() == ResultConfiguration.FAILURE.getCode()) {
        	resultDTO.failure(MessageConfiguration.LOGIN);
        	resultDTO.setMessage(result.getMessage());
        }
        return resultDTO;
    }



    @Override
    public LoginResultDTO logout(LoginParamDTO dto) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return null;
    }


    /**
     * 更新登录日志相关数据
     * @return
     */
    @Override
    public boolean changeLoginLogData(Serializable id) {
        Optional<AccountPO> accountPO =  accountDAO.findById((Long) id);
        Subject subject = SecurityUtils.getSubject();
        //如果没有查询到，则说明第一次进行登录
        if(accountPO.isPresent()){
            // 如果上一次登录时间为空 则说明第二次登陆
            accountPO.get().setLastLoginDate(accountPO.get().getCurrentLoginDate());
            accountPO.get().setCurrentLoginDate(new Date());
            subject.getSession(true).setAttribute(SystemConfiguration.DEFAULT_LAST_LOGIN_DATE,
                    DateUtils.getDateString(accountPO.get().getLastLoginDate()));
        }else{
            accountPO = Optional.ofNullable(new AccountPO());
            // id和user_id冗余相同
            accountPO.get().setUserId((Long) id);
            accountPO.get().setCurrentLoginDate(new Date());
            accountPO.get().setCreateDate(new Date());
            subject.getSession(true).setAttribute(SystemConfiguration.DEFAULT_LAST_LOGIN_DATE,"暂无上次登录时间");
        }
        try{
            return accountDAO.save(accountPO.get()) != null;
        }catch (Exception e){
            log.error("更新日志信息失败!",e);
            return false;
        }
    }

}
